import { getValue } from '@/config/RedisConfig'
import config from '../config/index'
import jwt from 'jsonwebtoken'
import fs from 'fs'
import path from 'path'
const getJWTPayload = (token) => {
  return jwt.verify(
    token.split(' ')[1],
    config.JWT_SECRET
    // ,(res, err) => {
    //   if (res === 1) {
    //     return res
    //   } else {
    //     return err
    //   }
    // }
    // ,(err) => {
    //   if (err) {
    //     err = {
    //       message: 'Token 已经失效，请重新获取发送邮件',
    //     }
    //   }
    //   }
  )
}

const generateToken = (payload) => {
  if (payload) {
    return jwt.sign(
      {
        ...payload,
      },
      config.JWT_SECRET,
      { expiresIn: '1d' }
    )
  } else {
    throw new Error('生成token失败')
  }
}
const checkCode = async (key, value) => {
  const redisData = await getValue(key)
  if (redisData != null) {
    if (redisData.toLowerCase() === value.toLowerCase()) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
}
//make-dir
const getStats = (path) => {
  return new Promise((resolve) => {
    // fs.stats(path, (err, stats)=>{
    //   if(err) {
    //     resolve (false)
    //   }else{
    //     resolve(stats)
    //   }
    // })
    fs.stat(path, (err, stats) => (err ? resolve(false) : resolve(stats)))
  })
}

const mkdir = (dir) => {
  return new Promise((resolve) => {
    fs.mkdir(dir, (err) => (err ? resolve(false) : resolve(true)))
  })
}
const dirExists = async (dir) => {
  const isExists = await getStats(dir)
  //该路径存在且不是文件就返回true
  if (isExists && isExists.isDirectory()) {
    return true
  } else if (isExists) {
    //路径存在但是是文件
    return false
  }
  //该路径不存在
  const tempDir = path.parse(dir).dir
  // /d/dir/path/pa 循环遍历 递归判断如果上级目录不存在，则残生上级目录
  const status = await dirExists(tempDir)
  if (status) {
    const result = await mkdir(dir)
    console.log(result)
    return result
  } else {
    return false
  }
}
const rename = (obj, key, newKey) => {
  if (Object.keys(obj).indexOf(key) !== -1) {
    obj[newKey] = obj[key]
    delete obj[key]
  }
  return obj
}
const rand = (n = 8) => {
  let sstring = ''
  let strings = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMnopQRSTUVWXYZ0123456789'
  for (let i = 0; i < n; i++) {
    let ind = Math.floor(Math.random() * strings.length)
    sstring += strings.charAt(ind)
  }
  return sstring
}
const getTempName = () => {
  return 'tm_' + rand() + '@tm.com'
}

export {
  checkCode,
  getJWTPayload,
  dirExists,
  rename,
  getTempName,
  generateToken,
}
